package org.jeecg.modules.mes.produce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.mes.client.SystemClient;
import org.jeecg.modules.mes.client.TransactionClient;
import org.jeecg.modules.mes.order.entity.MesProduceItem;
import org.jeecg.modules.mes.produce.entity.MesCommandbillInfo;
import org.jeecg.modules.mes.produce.entity.MesCommandbillPitem;
import org.jeecg.modules.mes.produce.entity.MesWorkbillInfo;
import org.jeecg.modules.mes.produce.service.IMesCommandbillInfoService;
import org.jeecg.modules.mes.produce.service.IMesCommandbillPitemService;
import org.jeecg.modules.mes.produce.service.IMesWorkbillInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

 /**
 * @Description: 制造中心-工单信息
 * @Author: jeecg-boot
 * @Date:   2020-10-20
 * @Version: V1.0
 */
@Api(tags="制造中心-工单信息")
@RestController
@RequestMapping("/produce/mesWorkbillInfo")
@Slf4j
public class MesWorkbillInfoController extends JeecgController<MesWorkbillInfo, IMesWorkbillInfoService> {
	 @Autowired
	 private IMesWorkbillInfoService mesWorkbillInfoService;
	 @Autowired
	 private IMesCommandbillInfoService mesCommandbillInfoService;

	 @Autowired
	 private IMesCommandbillPitemService mesCommandbillPitemService;

	 @Autowired
	 SystemClient systemClient;

	 @Autowired
	 TransactionClient transactionClient;

	/**
	 * 分页列表查询
	 *
	 * @param mesWorkbillInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "制造中心-工单信息-分页列表查询")
	@ApiOperation(value="制造中心-工单信息-分页列表查询", notes="制造中心-工单信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MesWorkbillInfo mesWorkbillInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MesWorkbillInfo> queryWrapper = QueryGenerator.initQueryWrapper(mesWorkbillInfo, req.getParameterMap());
		Page<MesWorkbillInfo> page = new Page<MesWorkbillInfo>(pageNo, pageSize);
		IPage<MesWorkbillInfo> pageList = mesWorkbillInfoService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
	 *   添加
	 *
	 * @param mesWorkbillInfo
	 * @return
	 */
	@AutoLog(value = "制造中心-工单信息-添加")
	@ApiOperation(value="制造中心-工单信息-添加", notes="制造中心-工单信息-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody MesWorkbillInfo mesWorkbillInfo) {
		mesWorkbillInfoService.save(mesWorkbillInfo);
		if(StringUtils.isNotBlank(mesWorkbillInfo.getAutomaticCommandbill())){
			String automatic = mesWorkbillInfo.getAutomaticCommandbill();//是否自动下达制令单
			//如果为是，则添加工单信息时，同时添加制令单
			if( automatic.equals("是")){
				MesCommandbillInfo commandbillInfo = new MesCommandbillInfo();
				commandbillInfo.setWorkbillCode(mesWorkbillInfo.getWorkbillCode());//工单号
				commandbillInfo.setControlType("正常");//管控类型
				BeanUtils.copyProperties(mesWorkbillInfo,commandbillInfo);
				commandbillInfo.setId(null);//主键设置为null
				commandbillInfo.setCreateBy(null);//创建人置为null
				commandbillInfo.setCreateTime(null);//创建时间设置为null
				commandbillInfo.setArriveTime(new Date());//下达时间
				commandbillInfo.setUninputNum(mesWorkbillInfo.getPlantNum());//未入库数量
				commandbillInfo.setClientName(mesWorkbillInfo.getClient());//客户名称
				commandbillInfo.setWorkbillId(mesWorkbillInfo.getId());//工单id
				commandbillInfo.setState("未完成");//状态
				commandbillInfo.setInputState("未完成");//入库状态

				if(StringUtils.isNotBlank(mesWorkbillInfo.getProduceId())){
					String orderId = mesWorkbillInfo.getProduceId();//生产订单id
					//通过订单id，获取生产订单子表数据
					List<MesProduceItem> produceItemList = transactionClient.listMesProduceItemByOrderId(orderId);
					if(produceItemList.size() != 0){
						mesCommandbillInfoService.save(commandbillInfo);
						for (MesProduceItem produceItem : produceItemList) {
							//新增制令单的同时，新增制令单BOM数据=生产订单子表
							MesCommandbillPitem commandbillPitem = new MesCommandbillPitem();
							//将生产订单子表的数据，复制单制令单BOM表中
							BeanUtils.copyProperties(produceItem,commandbillPitem);
							commandbillPitem.setOrderitemId(commandbillPitem.getId());//生产订单子表id
							commandbillPitem.setCommandbillId(commandbillInfo.getId());//制令单id
							commandbillPitem.setId(null);
							commandbillPitem.setDeliveryNum("0");//发料数量
							commandbillPitem.setUnglazeNum("0");//上料数量
							commandbillPitem.setWithdrawNum("0");//退料数量
							mesCommandbillPitemService.save(commandbillPitem);
						}
					}else {
						return Result.error("找不到生产订单子表的数据！请检查！");
					}
				}else {
					return Result.error("生产订单ID为空！请检查！");
				}
			}
		}
		return Result.ok("添加成功！");
	}

	 @PostMapping(value = "/produceAddInstruction")
	 public String produceAddInstruction(@RequestBody MesWorkbillInfo mesWorkbillInfo) {
		 mesWorkbillInfoService.save(mesWorkbillInfo);
		 return "添加成功！";
	 }



	/**
	 *  编辑
	 *
	 * @param mesWorkbillInfo
	 * @return
	 */
	@AutoLog(value = "制造中心-工单信息-编辑")
	@ApiOperation(value="制造中心-工单信息-编辑", notes="制造中心-工单信息-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody MesWorkbillInfo mesWorkbillInfo) {
		mesWorkbillInfoService.updateById(mesWorkbillInfo);
		return Result.ok("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "制造中心-工单信息-通过id删除")
	@ApiOperation(value="制造中心-工单信息-通过id删除", notes="制造中心-工单信息-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		QueryWrapper<MesCommandbillInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("workbill_id",id);
		mesCommandbillInfoService.remove(queryWrapper);
		mesWorkbillInfoService.removeById(id);
		return Result.ok("删除成功!");
	}

	 /**
	  * 生产订单删除时，调用这个模块，删除与生产订单关联的工单
	  * @param id
	  * @return
	  */
	 @DeleteMapping(value = "/deleteByPorderId")
	 public String deleteByPorderId(@RequestParam(name="id",required=true) String id) {
		 QueryWrapper<MesWorkbillInfo> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("produce_id", id);
		 List<MesWorkbillInfo> workbillInfoList = mesWorkbillInfoService.list(queryWrapper);
		 if(workbillInfoList.size() != 0 ){
			 for (MesWorkbillInfo workbillInfo : workbillInfoList) {
				 String workbillCode = workbillInfo.getWorkbillCode();//工单号
				 QueryWrapper<MesCommandbillInfo> wrapper = new QueryWrapper<>();
				 wrapper.eq("workbill_code", workbillCode);
				 mesCommandbillInfoService.remove(wrapper);
			 }
		 }
		 mesWorkbillInfoService.remove(queryWrapper);
		 return "删除成功!";
	 }

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "制造中心-工单信息-批量删除")
	@ApiOperation(value="制造中心-工单信息-批量删除", notes="制造中心-工单信息-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.mesWorkbillInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "制造中心-工单信息-通过id查询")
	@ApiOperation(value="制造中心-工单信息-通过id查询", notes="制造中心-工单信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		MesWorkbillInfo mesWorkbillInfo = mesWorkbillInfoService.getById(id);
		if(mesWorkbillInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(mesWorkbillInfo);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param mesWorkbillInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesWorkbillInfo mesWorkbillInfo) {
        return super.exportXls(request, mesWorkbillInfo, MesWorkbillInfo.class, "制造中心-工单信息");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesWorkbillInfo.class);
    }

}
